package qiniufile

import (
	"context"
	"fmt"

	"mall/common/globalkey"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"

	"github.com/zeromicro/go-zero/core/logx"
)

type PutFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPutFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PutFileLogic {
	return &PutFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PutFileLogic) PutFile(req *types.UpdateMediaFileReq) (resp *types.MediaFileInfoResp, err error) {
	data, err := l.svcCtx.AttachmentRpc.BackendCreateRecord(l.ctx, &attachmentclient.RecordInfo{
		Id:       req.Id,
		Diagnose: req.Method,
		Bucket:   req.Bucket,
		Key:      req.Key,
		Style:    req.Style,
	})
	if err != nil {
		return nil, err
	}

	if data.Id == nil {
		return &types.MediaFileInfoResp{
			BaseDataInfo: types.BaseDataInfo{
				Msg: l.svcCtx.Trans.Trans(l.ctx, i18n.Failed),
			},
		}, nil
	}

	var url string
	if data.Key != nil && len(*data.Key) > 0 {
		url = fmt.Sprintf("%s/%s", l.svcCtx.Config.NfsConf.StaticUrl, *data.Key)
	}

	var status uint32
	if data.DelStatus != nil && *data.DelStatus > 0 {
		status = uint32(globalkey.PostStatusTrash)
	} else if data.Status != nil && *data.Status > 0 {
		status = uint32(globalkey.PostStatusDraft)
	} else {
		status = uint32(globalkey.PostStatusPublish)
	}

	return &types.MediaFileInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.MediaFileInfo{
			BaseUUIDInfo: types.BaseUUIDInfo{
				Id:        data.Id,
				CreatedAt: data.CreatedAt,
				UpdatedAt: data.UpdatedAt,
				DeletedAt: data.ExpiredAt,
			},
			UserId:        data.EndUser,
			ParentId:      data.ParentId,
			Url:           &url,
			Bucket:        data.Bucket,
			FileType:      data.Type,
			MimeType:      data.MimeType,
			Status:        &status,
			Path:          data.Key,
			RestoreStatus: data.RestoreStatus,
			Size:          data.Size,
			Md5:           data.Md5,
			MetaValue:     data.MetaValue,
		},
	}, nil
}
